package com.haoze.nurse.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.nurse.component.PatientComponent;
import com.haoze.nurse.dao.*;
import com.haoze.nurse.dto.*;
import com.haoze.nurse.enumeration.NurseEnum;
import com.haoze.nurse.enumeration.NurseFileTypeEnum;
import com.haoze.nurse.enumeration.StateEnum;
import com.haoze.nurse.model.NurseFileDataDetailEntity;
import com.haoze.nurse.model.NurseFileIndexEntity;
import com.haoze.nurse.service.NursePatientService;
import com.haoze.nurse.vo.NurseFileData;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class NursePatientServiceImpl implements NursePatientService {

    private static final Logger logger = LoggerFactory.getLogger(NursePatientServiceImpl.class);

    @Resource
    NursePatientMapper nursePatientMapper;

    @Resource
    PatientMapper patientMapper;

    @Resource
    NurseDiagMapper nurseDiagMapper;

    @Resource
    NurseFileMapper nurseFileMapper;

    @Resource
    NurseFileIndexMapper nurseFileIndexMapper;

    @Resource
    PatientComponent patientComponent;


    @Value("${his.url.operationUrl}")
    private String operationUrl;
    @Value("${his.url.operationUrl2}")
    private String operationUrl2;

    @Resource
    NurseOrdersMapper nurseOrdersMapper;

    @Value("${spring.profiles.active}")
    private String activeType;

    @Value("${his.url.cost}")
    private String cost;

    @Value("${his.url.environmentFlag}")
    private String environmentFlag;

    private ExecutorService fixedThreadPool;

    public NursePatientServiceImpl() {
        fixedThreadPool = Executors.newFixedThreadPool(10);
    }


    @Override
    public Result getDepts() {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, String>> deptList = nursePatientMapper.getDepts(userId);
        return ResultGenerator.genOkResult(deptList);
    }

    /**
     * 获取病人信息
     *
     * @param inpatNum 入院号
     * @return
     */
    @Override
    public Result getPatientMsg(String inpatNum, boolean isHide) {
        if (StringUtils.isBlank(inpatNum)) {
            return ResultGenerator.genOkResult();
        }
        NursePatientMsgDTO dto = nursePatientMapper.getPatientInfo(inpatNum);
        if (dto.getBirthDay() != null && dto.getInDateTime() != null) {
            Calendar c1 = Calendar.getInstance();
            c1.setTime(DateUtil.stringToDate(dto.getBirthDay()));
            Calendar c2 = Calendar.getInstance();
            c2.setTime(DateUtil.stringToDate(dto.getInDateTime()));

            int[] times = DateUtil.getTimeIntervalArray(c2, c1);
            int years = times[0];
            int months = times[1];
            int days = times[2];
            int hours = times[3];
            int minutes = times[4];

            if (years >= 3) {
                dto.setAge(years + "岁");
            } else if (years >= 1 && years < 3) {
                dto.setAge(years + "岁" + (months == 0 ? "" : months + "月"));
            } else if (years < 1 && months >= 1) {
                dto.setAge(months + "月" + (days == 0 ? "" : days + "天"));
            } else if (days == 29) {
                dto.setAge(days + "天");
            } else if (days <= 28 && days >= 1) {
                dto.setAge(days + "天" + (hours == 0 ? "" : hours + "小时"));
            } else if (days < 1 && hours >= 1) {
                dto.setAge(hours + "小时" + (minutes == 0 ? "" : minutes + "分钟"));
            } else if (hours < 1 && minutes >= 1) {
                dto.setAge(minutes + "分钟");
            } else {
                dto.setAge((dto.getAgeYear() == null ? "" : dto.getAgeYear() + "岁") + (dto.getAgeMonth() == null ? "" : dto.getAgeMonth() + "月") + (dto.getAgeDay() == null ? "" : dto.getAgeDay() + "天"));
            }

        } else { // 当出生日期或者入院日期无效则采用下面策略计算时间
            if (dto.getAgeDay() == null) {
                dto.setAge((dto.getAgeYear() == null ? "" : dto.getAgeYear() + "岁") + (dto.getAgeMonth() == null ? "" : dto.getAgeMonth() + "月"));
            } else {
                if (dto.getMinutes() == null) {
                    dto.setAge((dto.getAgeYear() == null ? "" : dto.getAgeYear() + "岁") + (dto.getAgeMonth() == null ? "" : dto.getAgeMonth() + "月") + (dto.getAgeDay() == null ? "" : dto.getAgeDay() + "天"));
                } else {
                    int days = Integer.parseInt(dto.getMinutes()) / 60 / 24;
                    int hour = Integer.parseInt(dto.getMinutes()) / 60 % 24;
                    dto.setAge((days == 0 ? (hour == 0 ? "" : hour + "小时") : days + "天"));
                }
            }
        }

        if (dto != null) {

            if (dto.getSex() != null && dto.getSex().length() > 0) {
                dto.setSex(dto.getSex().substring(0, 1));
            }

            // 过滤诊断
            // 获取护士修改后绑定到文书的诊断id
            String diagName = "";
            String diagId = nurseDiagMapper.queryDiagIdByInpatNum(inpatNum);
            if (StringUtils.isNotBlank(diagId)) {
                // 获取护士修改的诊断名称
                diagName = nurseDiagMapper.queryDiagByDiagId(diagId);
                dto.setDiagName(diagName);
            } else {
                //取病案首页his出院诊断
                if ("prod".equals(activeType)) {
                    String[] inpatNums = inpatNum.split("-");
                    String param = "as_patient_id=" + inpatNums[0] + "&al_visit_id=" + inpatNums[1];
                    JSONObject jsonObject = HttpConnectUtils.sendGet("http://172.20.91.56:8181/P_VsitInfo_Query_03", param);
                    if ("1".equals(jsonObject.get("error_id").toString())) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (Object jsonObject1 : jsonArray) {
                            JSONObject object = JSONObject.parseObject(jsonObject1.toString());
                            if (object.get("DIAGNOSIS_TYPE") != null && "2".equals(object.get("DIAGNOSIS_TYPE").toString())) {
                                diagName = object.get("DIAGNOSIS_DESC").toString();
                                break;
                            }
                        }
                    }
                }
                if (StringUtils.isNotBlank(diagName)) {
                    dto.setDiagName(diagName);
                } else {
                    // 获取智慧病历出院诊断/修正诊断/入院诊断
                    diagName = nurseDiagMapper.queryOutHospitalDiag(inpatNum);
                    if (StringUtils.isNotBlank(diagName)) {
                        dto.setDiagName(diagName);
                    } else {
                        //获取his门诊诊断
                        diagName = nurseDiagMapper.queryOutpatientDiag(inpatNum);
                        dto.setDiagName(diagName);
                    }
                }
            }
            // 截取科室名称返回
            if (dto.getDeptName().contains(")")) {
                String[] strings = dto.getDeptName().split("\\)");
                if (strings.length > 0) {
                    dto.setDeptName(strings[0] + ")");
                }
            } else if (dto.getDeptName().contains("）")) {
                String[] strings = dto.getDeptName().split("）");
                if (strings.length > 0) {
                    dto.setDeptName(strings[0] + "）");
                }
            }

            // 处理床号,当出院病人床号为0时显示最近一次护理记录单中记录的床号
            if ("0".equals(dto.getBedNo())) {
                // 获取记录时间最近的护理记录，从中获取床号
                String bedNo = nurseFileMapper.getLatestBedNo(inpatNum);
                if (StringUtils.isNotEmpty(bedNo)) {
                    dto.setBedNo(bedNo);
                }

            }
        } else {
            dto = new NursePatientMsgDTO();
        }
        //母婴同室 新生儿使用母亲的孕次产次
        if (inpatNum.contains("B")) {
            inpatNum = inpatNum.split("B")[0] + "-" + inpatNum.split("-")[1];
        }
        NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(NurseFileTypeEnum.LabourA.getEnumValue(), inpatNum);
        if (fileIndexEntity != null && !StringUtils.isAllBlank(fileIndexEntity.getPregnancyCount(), fileIndexEntity.getProductionCount(), fileIndexEntity.getExpectedDate())) {
            dto.setPregnancyCount(StringUtils.isNotBlank(fileIndexEntity.getPregnancyCount()) ? fileIndexEntity.getPregnancyCount() : "0");
            dto.setProductionCount(StringUtils.isNotBlank(fileIndexEntity.getProductionCount()) ? fileIndexEntity.getProductionCount() : "0");
            dto.setExpectedDate(StringUtils.isNotBlank(fileIndexEntity.getExpectedDate()) ? fileIndexEntity.getExpectedDate() : "");
        } else {
            List<Map<String, Object>> gpMap = nurseFileIndexMapper.getGPFromFileIndex(inpatNum);//从智慧病历获取孕次+产次+预产期
            String ck_ycq = "", pregnancyCount = "", productionCount = "";
            for (Map gpmap : gpMap) {
                if (gpmap.get("VAR_CODE") != null) {
                    if (StateEnum.CK_YCQ.getValue().equals(gpmap.get("VAR_CODE").toString())) {
                        ck_ycq = (String) gpmap.get("DATA_VALUE");
                    }
                    if (StateEnum.ZHENDUAN.getValue().equals(gpmap.get("VAR_CODE").toString())) {
                        String zhenduan = "";
                        if (gpmap.get("DATA_VALUE") != null) {
                            zhenduan = (String) gpmap.get("DATA_VALUE");
                            pregnancyCount = zhenduan.substring(1, 2);
                            productionCount = zhenduan.substring(3, 4);
                        }
                    }
                }
            }
            if (StringUtils.isBlank(productionCount)) {
                productionCount = nurseFileIndexMapper.getSecondProductionCount(inpatNum);//获取产次第二来源 产次=足月产次+早产产次  孕次=足月产次+早产产次+流产产次+1
            }
            if (StringUtils.isBlank(pregnancyCount)) {
                pregnancyCount = nurseFileIndexMapper.getSecondPregnancyCount(inpatNum);
            }
            if (!StringUtils.isAllBlank(pregnancyCount, productionCount, ck_ycq)) {
                dto.setPregnancyCount(StringUtils.isBlank(pregnancyCount) ? "0" : pregnancyCount);
                dto.setProductionCount(StringUtils.isBlank(productionCount) ? "0" : productionCount);
                dto.setExpectedDate(ck_ycq);
            } else {
                dto.setPregnancyCount("0");
                dto.setProductionCount("0");
                dto.setExpectedDate("");
            }
        }
        if(isHide){
            hidePatientInfo(dto,inpatNum);
        }

        return ResultGenerator.genOkResult(dto);
    }

    private void hidePatientInfo(NursePatientMsgDTO patientInfo, String inpatNum) {
        Map<String, String> map = nurseFileIndexMapper.getDesensitization(inpatNum);
        if(map==null){
            //隐藏名称
            patientInfo.setPatName(MyStringUtil.getStarStringExclude(patientInfo.getPatName(),1,0));
            //隐藏住院号
            patientInfo.setMedicalNum(MyStringUtil.getStarStringExclude(patientInfo.getMedicalNum(),1,0));
            patientInfo.setInpatNum(MyStringUtil.getStarStringExclude(patientInfo.getMedicalNum(),1,0));
        }else if(org.springframework.util.StringUtils.hasLength(map.get("columnId"))) {
            String desensitizaColumnId = map.get("columnId");
            if(desensitizaColumnId.contains(NurseEnum.HIDE_NAME.getIndex())){
                //隐藏名称
                patientInfo.setPatName(MyStringUtil.getStarStringExclude(patientInfo.getPatName(),1,0));
            }
            if(desensitizaColumnId.contains(NurseEnum.HIDE_INPATNUM.getIndex())){
                //隐藏住院号
                patientInfo.setMedicalNum(MyStringUtil.getStarStringExclude(patientInfo.getMedicalNum(),1,0));
                patientInfo.setInpatNum(MyStringUtil.getStarStringExclude(patientInfo.getMedicalNum(),1,0));
            }
        }
    }

    @Override
    public Result getNursePatients(String wardId, String search, String status) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, String>> patientList = new ArrayList<>();

        String inpatNumSearch = "";
        String userName = "";
        if (search != null && search.length() > 0) {
            boolean isInt = Pattern.compile("^[0-9]").matcher(search.substring(0, 1)).find();
            if (isInt) {
                inpatNumSearch = search;
            } else {
                userName = search;
            }
        }

        if (status.equals("0") || status.equals("")) { // 获取入院病人1
            if (inpatNumSearch.equals("") && userName.equals("")) {
                // 住院病人
                patientList = nursePatientMapper.getNursePatientsInHospital(wardId, inpatNumSearch, userName);
            } else {
                // 住院病人
                patientList = nursePatientMapper.getNursePatientsInHospitalBySearch(wardId, inpatNumSearch, userName);
            }
            String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
            List<String> nursingGradeList = Arrays.asList(StateEnum.IJHL.getValue(), StateEnum.IJHLEK.getValue(), StateEnum.IIJHL.getValue(),
                    StateEnum.IIIJHLEK.getValue(), StateEnum.IIIJHL.getValue(), StateEnum.IIIJHLEK.getValue(),
                    StateEnum.YJHL.getValue(), StateEnum.EJHL.getValue(), StateEnum.SJHL.getValue(),
                    StateEnum.TJHL.getValue(), StateEnum.TJHLEK.getValue(), StateEnum.JHBFYJHL.getValue(),
                    StateEnum.JHBFEJHL.getValue(), StateEnum.JHBFTJHL.getValue());
            List<String> inpatNumList = new CopyOnWriteArrayList<>();
            for (Map<String, String> map : patientList) {
                inpatNumList.add(map.get("inpatNum"));
            }

            List<Map<String, String>> nursingGradeLists = new CopyOnWriteArrayList<>();
            if(!CollectionUtils.isEmpty(inpatNumList)) {
                nursingGradeLists = nursePatientMapper.queryNursingGradeByInpatNum(inpatNumList, dateTime, nursingGradeList);
            }
            for (Map<String, String> map : patientList) {
                String nursingGrade=null;
                // 处理护理等级，截取第一个字显示（现在通过颜色显示）
               /* String nursingGrade = map.get("nursingGrade");
                if (nursingGrade != null && nursingGrade.length() > 0) {
                    String tempNursingGrade = nursingGrade.substring(0, 1);
                    map.put("nursingGrade", tempNursingGrade);
                }*/
               Map<String, String> filterNursingGrade = nursingGradeLists.stream().filter(s -> ((String)map.get("inpatNum")).equals(s.get("inpatNum"))).findFirst().orElse(null);
               if(filterNursingGrade!=null){
                    if(StateEnum.TJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.TJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFTJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade=StateEnum.TJHL.getText();
                    }else if(StateEnum.IJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.YJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFYJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade=StateEnum.YJHL.getText();
                    }else if(StateEnum.IIJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IIJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.EJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFEJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade=StateEnum.EJHL.getText();
                    }else if(StateEnum.IIIJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IIIJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.SJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade=StateEnum.SJHL.getText();
                    }
                }

                if (StringUtils.isNotBlank(nursingGrade)) {
                    String tempNursingGrade = nursingGrade.substring(0, 1);
                    map.put("nursingGrade", tempNursingGrade);
                }else{
                    map.put("nursingGrade", "");
                }
                if (map.get("inDatetime") != null && map.get("inDatetime").length() > 10) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date currDate = new Date();
                    String currDateStr = sdf.format(currDate);
                    String inDatetimeStr = map.get("inDatetime").substring(0, 10);
                    if (currDateStr.equals(inDatetimeStr)) {
                        map.put("today", "1");
                    }
                }
            }

//            patientList.parallelStream().forEach(x-> {
//                Map<String, String> conditions = patientMapper.queryConditionInfo(x.get("inpatNum"));//护理登记  病重 药物过敏 危险标识
//                if(null != conditions) {
//                    if (StringUtils.isBlank(conditions.get("nursingGrade"))) {
//                        x.put("nursingGrade", "");//护理等级
//                    } else {
//                        x.put("nursingGrade", conditions.get("nursingGrade"));//护理等级
//                    }
//                }
//            });
            return ResultGenerator.genOkResult(patientList);
        } else if (status.equals("1")) { // 获取出院病人

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.MONTH, -1);
            Date lastMonth = calendar.getTime();

            patientList = nursePatientMapper.getNursePatientsOutHospital(wardId, inpatNumSearch, userName, lastMonth);

            for (Map<String, String> map : patientList) {
                // 处理护理等级，截取第一个字显示（现在通过颜色显示）
                String nursingGrade = map.get("nursingGrade");
                if (nursingGrade != null && nursingGrade.length() > 0) {
                    String tempNursingGrade = nursingGrade.substring(0, 1);
                    map.put("nursingGrade", tempNursingGrade);
                }

                if (map.get("inDatetime") != null && map.get("inDatetime").length() > 10) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date currDate = new Date();
                    String currDateStr = sdf.format(currDate);
                    String inDatetimeStr = map.get("inDatetime").substring(0, 10);
                    if (currDateStr.equals(inDatetimeStr)) {
                        map.put("today", "1");
                    }
                }
            }
//            patientList.parallelStream().forEach(x-> {
//                Map<String, String> conditions = patientMapper.queryConditionInfo(x.get("inpatNum"));//护理登记  病重 药物过敏 危险标识
//                if(conditions ==null || StringUtils.isBlank(conditions.get("nursingGrade"))){
//                    x.put("nursingGrade", "");//护理等级
//                }else{
//                    x.put("nursingGrade", conditions.get("nursingGrade"));//护理等级
//                }
//            });
            return ResultGenerator.genOkResult(patientList);
        } else if (status.equals("2")) {
            // 获取转科转病区患者 TODO: 功能完成后需要切换日期为当前日期
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(new Date());
//            calendar.set(Calendar.HOUR_OF_DAY, -24*13);
            Date theCurrDate = new Date();
            // 1.获取转科转病区信息滞留时长
            String transLeaveTime = nurseFileMapper.queryVarValueByVarCode("zkzlsc");

//            List list = nurseFileIndexMapper.queryLeaveTransRecord(lastMonth, Integer.parseInt(transLeaveTime), wardId);

            patientList = nursePatientMapper.getNursePatientsTrans(wardId, inpatNumSearch, userName, theCurrDate, Integer.parseInt(transLeaveTime));

            for (Map<String, String> map : patientList) {
                // 处理护理等级，截取第一个字显示（现在通过颜色显示）
                String nursingGrade = map.get("nursingGrade");
                if (nursingGrade != null && nursingGrade.length() > 0) {
                    String tempNursingGrade = nursingGrade.substring(0, 1);
                    map.put("nursingGrade", tempNursingGrade);
                }

                if (map.get("inDatetime") != null && map.get("inDatetime").length() > 10) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date currDate = new Date();
                    String currDateStr = sdf.format(currDate);
                    String inDatetimeStr = map.get("inDatetime").substring(0, 10);
                    if (currDateStr.equals(inDatetimeStr)) {
                        map.put("today", "1");
                    }
                }
            }

//            patientList.parallelStream().forEach(x-> {
//                Map<String, String> conditions = patientMapper.queryConditionInfo(x.get("inpatNum"));//护理登记  病重 药物过敏 危险标识
//                if(StringUtils.isBlank(conditions.get("nursingGrade"))){
//                    x.put("nursingGrade", "");//护理等级
//                }else{
//                    x.put("nursingGrade", conditions.get("nursingGrade"));//护理等级
//                }
//            });
            return ResultGenerator.genOkResult(patientList);
        } else {
            patientList.parallelStream().forEach(x -> {
                Map<String, String> conditions = new HashMap<>();
                List<Map<String, String>> condList = patientMapper.queryConditionInfo(x.get("inpatNum"));//护理登记  病重 药物过敏 危险标识
                for (Map<String, String> cond : condList) {
                    if (cond != null) {
                        if ("drugBacterialInfection".equals(cond.get("type"))) {
                            conditions.put("drugBacterialInfection", cond.get("data"));
                        } else if ("nursingGrade".equals(cond.get("type"))) {
                            conditions.put("nursingGrade", cond.get("data"));
                        } else if ("responsibleNursePerson".equals(cond.get("type"))) {
                            conditions.put("responsibleNursePerson", cond.get("data"));
                        } else if ("disdaseState".equals(cond.get("type"))) {
                            conditions.put("disdaseState", cond.get("data"));
                        } else if ("allergicDrugs".equals(cond.get("type"))) {
                            conditions.put("allergicDrugs", cond.get("data"));
                        } else if ("eatingHabits".equals(cond.get("type"))) {
                            conditions.put("eatingHabits", cond.get("data"));
                        }
                    }
                }
                if (StringUtils.isBlank(conditions.get("nursingGrade"))) {
                    x.put("nursingGrade", "");//护理等级
                } else {
                    x.put("nursingGrade", conditions.get("nursingGrade"));//护理等级
                }
            });
            return ResultGenerator.genOkResult(patientList);
        }

    }

    public Result getNursePatients2(String wardId, String search, String status,int page,int pageSize){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, String>> patientList = new ArrayList<>();

        String inpatNumSearch = "";
        String userName = "";
        if (search != null && search.length() > 0) {
            boolean isInt = Pattern.compile("^[0-9]").matcher(search.substring(0, 1)).find();
            if (isInt) {
                inpatNumSearch = search;
            } else {
                userName = search;
            }
        }

        if (status.equals("0") || status.equals("")) { // 获取入院病人1
            if (inpatNumSearch.equals("") && userName.equals("")) {
                // 住院病人
                patientList = nursePatientMapper.getNursePatientsInHospital(wardId, inpatNumSearch, userName);
            } else {
                // 住院病人
                patientList = nursePatientMapper.getNursePatientsInHospitalBySearch(wardId, inpatNumSearch, userName);
            }
            return ResultGenerator.genOkResult(patientList);
        } else if (status.equals("1")) { // 获取出院病人
            wardId = null;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.MONTH, -1);
            Date lastMonth = calendar.getTime();
            PageHelper.startPage(page, pageSize);
            patientList = nursePatientMapper.getNursePatientsOutHospital2(inpatNumSearch, userName, lastMonth);
            return ResultGenerator.genOkResult(patientList);
        }
        return ResultGenerator.genOkResult(patientList);
    }

    @Override
    public List<Map<String, String>> searchDiags(String diag) {

        if (diag.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        String pinyin;
        try {
            pinyin = ChineseCharactersCode.getPinyinCode(diag);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            logger.error("转拼音出错，字符异常。");
            return new ArrayList<>();
        }
        boolean isPinyin = false;
        if (diag.equals(pinyin)) {
            isPinyin = true;
        }

        List<Map<String, String>> diagList = nurseDiagMapper.queryDiags(isPinyin, pinyin.toUpperCase(), diag);

        return diagList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result bondDiag(String diagId, String inpatNum) {
        if (StringUtils.isBlank(inpatNum)) {
            return ResultGenerator.genFailedResult("文书不存在无法修改诊断");
        }

        // 先查询该诊断是否包含在诊断字典中，如果不包含则不能保存
        String diagName = nurseDiagMapper.queryDiagByDiagId(diagId);

        // 有诊断
        if (StringUtils.isNotBlank(diagName)) {
            // 绑定诊断到文书
            nurseFileIndexMapper.bondNurseFileIndexByDiagId(diagId, inpatNum);

            return ResultGenerator.genOkResult("诊断修改成功");

        } else {
            return ResultGenerator.genOkResult("无法查到当前诊断");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result bondGestationInfo(String inpatNum, String pregnancyCount, String productionCount, String expectedDate) {
        NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(NurseFileTypeEnum.LabourA.getEnumValue(), inpatNum);
        if (fileIndexEntity != null) {
//            if (StringUtils.isNotBlank(pregnancyCount))
            nursePatientMapper.updatePregnancyCount(inpatNum, pregnancyCount);
//            if (StringUtils.isNotBlank(pregnancyCount))
            nursePatientMapper.updateProductionCount(inpatNum, productionCount);
//            if (StringUtils.isNotBlank(pregnancyCount))
            nursePatientMapper.updateExpectedDate(inpatNum, expectedDate);

            return ResultGenerator.genOkResult("保存成功");
        } else {
            String tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbcsyjl");
            // 第一次点击新建会创建主文书记录
            fileIndexEntity = new NurseFileIndexEntity();
            fileIndexEntity.setFileIndexId(UUIDUtil.randomString());
            fileIndexEntity.setDataVersion(1);
            fileIndexEntity.setHospitalId("");
            fileIndexEntity.setTplId(StringUtils.isNotBlank(tplId) ? tplId : "");
            fileIndexEntity.setRecordType(NurseFileTypeEnum.LabourA.getEnumValue());
            fileIndexEntity.setInpatNum(inpatNum);
            fileIndexEntity.setNurseCustomizeExpand("");
            // TODO: 创建人编号应该从请求头中获取
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                    .getHeader("zuul_id");

            fileIndexEntity.setCreateId(userId == null ? "创建人ID" : userId);
            // TODO: 记录类型名-记录人-记录时间
            fileIndexEntity.setNurseFileName("");

            nurseFileIndexMapper.insert(fileIndexEntity);

            if (StringUtils.isNotBlank(pregnancyCount)) {
                nursePatientMapper.updatePregnancyCount(inpatNum, pregnancyCount);
            }
            if (StringUtils.isNotBlank(productionCount)) {
                nursePatientMapper.updateProductionCount(inpatNum, productionCount);
            }
            if (StringUtils.isNotBlank(expectedDate)) {
                nursePatientMapper.updateExpectedDate(inpatNum, expectedDate);
            }

            return ResultGenerator.genOkResult("保存成功");
        }

    }

    @Override
    public Result getLMP(String inpatNum) {
        Map<String, Object> lmpMap = nursePatientMapper.getLmpByInpatNum(inpatNum);

        String dataValue = "";

        if (lmpMap != null) {//有创建
            try {
                if (lmpMap.get("DATA_VALUE") != null) {
                    if (lmpMap.get("DATA_VALUE") instanceof Clob) {
                        Clob clob = (Clob) lmpMap.get("DATA_VALUE");
                        BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                        dataValue = FileCopyUtils.copyToString(reader);
                    } else {
                        dataValue = (String) lmpMap.get("DATA_VALUE");
                    }
                }
            } catch (SQLException | IOException e) {
                logger.error("转换对象出错。", e);
            }
        }
        Map returnMap = new HashMap();
        List<NurseFileData> list = new ArrayList<>();

        // 封装孕周，孕天数据节点
        String gestationalWeekId = nurseFileMapper.queryVarValueByVarCode(StateEnum.GESTATIONAL_WEEK.getValue());
        String gestationalDayId = nurseFileMapper.queryVarValueByVarCode(StateEnum.GESTATIONAL_DAY.getValue());
        NurseFileData weekFileData = new NurseFileData();

        Element weekElement = nurseFileMapper.queryElementById(gestationalWeekId);
        weekFileData.setElement(weekElement);
        NurseFileDataDetailEntity weekFileIndexDataEntity = new NurseFileDataDetailEntity();

        // TODO: 暂时写成默认值
        weekFileIndexDataEntity.setDataValue("");
        weekFileIndexDataEntity.setDataCode("");
        weekFileIndexDataEntity.setVarCode(weekElement.getVarCode());
        weekFileIndexDataEntity.setElementId(weekElement.getId());
        weekFileIndexDataEntity.setElementProperty(weekElement.getElementPropertyFormat());
        weekFileIndexDataEntity.setElementType(weekElement.getType());
        weekFileIndexDataEntity.setShowIdentification("0");
        weekFileIndexDataEntity.setPrintIdentification("0");
        weekFileIndexDataEntity.setDeleteIdentification("0");
        weekFileIndexDataEntity.setEditIdentification("0");

        weekFileIndexDataEntity.setExpandFieldsMap(new HashMap<>());
        weekFileData.setFileIndexDataEntity(weekFileIndexDataEntity);
        weekFileData.setEmrFileDataList(new ArrayList<>());

        list.add(weekFileData);

        // 入量固定良好拼装================================================
        NurseFileData dayFileData = new NurseFileData();

        Element dayElement = nurseFileMapper.queryElementById(gestationalDayId);

        dayFileData.setElement(dayElement);
        NurseFileDataDetailEntity dayFileIndexDataEntity = new NurseFileDataDetailEntity();
        dayFileIndexDataEntity.setDataValue("");
        dayFileIndexDataEntity.setDataCode("");
        dayFileIndexDataEntity.setVarCode(dayElement.getVarCode());
        dayFileIndexDataEntity.setElementType(dayElement.getType());
        dayFileIndexDataEntity.setElementId(dayElement.getId());
        dayFileIndexDataEntity.setElementProperty(dayElement.getElementPropertyFormat());
        dayFileIndexDataEntity.setShowIdentification("0");
        dayFileIndexDataEntity.setPrintIdentification("0");
        dayFileIndexDataEntity.setDeleteIdentification("0");
        dayFileIndexDataEntity.setEditIdentification("0");

        dayFileData.setFileIndexDataEntity(dayFileIndexDataEntity);
        dayFileData.setEmrFileDataList(new ArrayList<>());
        list.add(dayFileData);

        returnMap.put("list", list);
        returnMap.put("menstruationStopTime", dataValue == null ? "" : dataValue);

        return ResultGenerator.genOkResult(returnMap);

    }

    @Override
    public Result getBabyNum(String inpatNum) {
        String[] inpatInfo = inpatNum.split("-");
        String inpatNumB = inpatInfo[0] + "B";
        Integer babyNum = nursePatientMapper.getBabyNum(inpatNumB);
        return ResultGenerator.genOkResult(babyNum);
    }

    @Override
    public Result getPatientInfoCards(PatientCardsDTO cardsDTO) {
        cardsDTO.setCurrTime(new Date());
        PageHelper.startPage(cardsDTO.getPage(), cardsDTO.getPageSize());
        long time1 = System.currentTimeMillis();
        int total = 0;

        if ("95037CF5C9465245E053ED5B14ACFD88".equals(cardsDTO.getWardId()) || "95037CF5C9475245E053ED5B14ACFD88".equals(cardsDTO.getWardId())) {
            //麻醉室
            List<Map<String, String>> deptList = new ArrayList<Map<String, String>>();
            Map<String, String> map = new HashMap<String, String>();
            map.put("recovery", "95037CF5C9465245E053ED5B14ACFD88");
            map.put("operation", "F0F3BC5868CE47F583CB08EC6E46B1D6");
            deptList.add(map);
            map = new HashMap<String, String>();
            map.put("recovery", "95037CF5C9475245E053ED5B14ACFD88");
            map.put("operation", "5D04523554944A30A5FB81F57E985763");
            deptList.add(map);
            String operationWardId = null;
            String deptCode = null;
            for (Map<String, String> dMap : deptList) {
                if (cardsDTO.getWardId().equals(dMap.get("recovery"))) {
                    operationWardId = dMap.get("operation");
                }
            }
            Map<String, String> deptInfo = patientMapper.getDeptCodeById(operationWardId);
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            if (deptInfo != null) {
                deptCode = deptInfo.get("deptCode").replace("H", "");
                //调用his
                Map<String, String> params = new HashMap<String, String>();
                params.put("as_patient_id", "");
                params.put("as_operating_room", deptCode);
                params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10003.getKey());
                System.out.println(JSON.toJSONString(params));
                JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("获取复苏室数据失败");
                }
                if (null != jsonObject) {
                    Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                    if (resInt < 0) {
                        //return ResultGenerator.genFailedResult("HIS接口调用失败");
                        //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                    }
                }
                if (jsonObject.getString("data") != null) {
                    list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                    });
                    //查询条件 住院号和姓名
                    if (StringUtils.isNotBlank(cardsDTO.getSearch())) {
                        list = list.stream().filter(patient -> (patient.get("PATIENT_ID").indexOf(cardsDTO.getSearch()) >= 0 || patient.get("name").indexOf(cardsDTO.getSearch()) >= 0)).collect(Collectors.toList());
                    }
                    list.stream().forEach(patient -> {
                        //根据住院号查询patient_in_hospital表中数据
                        String inpatNum = patient.get("PATIENT_ID").toString() + "-1";
                        patient.put("inpatNum", inpatNum);
                        Map<String, String> patientMap = patientMapper.queryPatientByInpatNum(inpatNum);
                        if (patientMap != null) {
                            patient.putAll(patientMap);
                            Map detail = getIdentification(inpatNum);
                            patient.putAll(detail);
                        } else {
                            patient.put("bedNo", "0");//不能为null,排序会报错
                        }
                        patient.put("currentWardDeptName", deptInfo.get("deptName"));
                    });
                    if (StringUtils.isNotBlank(cardsDTO.getBedNo())) {
                        list = list.stream().filter(patient -> (Integer.parseInt(patient.get("bedNo")) == Integer.parseInt(cardsDTO.getBedNo()))).collect(Collectors.toList());
                    }
                    if (!CollectionUtils.isEmpty(list)) {
                        //排序
                        list = list.stream().sorted(Comparator.comparing(PatientServiceImpl::comparingByBedNo)).collect(Collectors.toList());
                        total = list.size();
                        list = list.stream().skip((cardsDTO.getPage() - 1) * cardsDTO.getPageSize()).limit(cardsDTO.getPageSize()).collect(Collectors.toList());
                    }
                }
                for (Map<String, String> item : list) {
                    item.put("infoType", "anaesthesia");//其他
                }
                PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
                pageInfo.setTotal(total);
                return ResultGenerator.genOkResult(pageInfo);
            }
            //城中                                                             //阳湖
        } else if ("F0F3BC5868CE47F583CB08EC6E46B1D6".equals(cardsDTO.getWardId()) || cardsDTO.getWardId().equals("5D04523554944A30A5FB81F57E985763")) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String deptCode = null;
            //手术室
            Map<String, String> deptInfo = patientMapper.getDeptCodeById(cardsDTO.getWardId());
            if (deptInfo != null) {
                deptCode = deptInfo.get("deptCode").replace("H", "");
                //调用his
                Map<String, String> params = new HashMap<String, String>();
                params.put("as_patient_id", "");
                params.put("as_operating_room", deptCode);
                params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10002.getKey());
                System.out.println(JSON.toJSONString(params));
                JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("获取手术数据失败");
                }
                if (null != jsonObject) {
                    Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                    if (resInt < 0) {
                        //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                    }
                }
                if (jsonObject.getString("data") != null) {
                    list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                    });
                    //查询条件 住院号和姓名
                    if (StringUtils.isNotBlank(cardsDTO.getSearch())) {
                        list = list.stream().filter(patient -> (patient.get("PATIENT_ID").indexOf(cardsDTO.getSearch()) >= 0 || patient.get("name").indexOf(cardsDTO.getSearch()) >= 0)).collect(Collectors.toList());
                    }
                    list.stream().forEach(patient -> {
                        //根据住院号查询patient_in_hospital表中数据
                        String inpatNum = patient.get("PATIENT_ID").toString() + "-1";
                        patient.put("inpatNum", inpatNum);
                        Map<String, String> patientMap = patientMapper.queryPatientByInpatNum(inpatNum);
                        if (patientMap != null) {
                            patient.putAll(patientMap);
                            Map detail = getIdentification(inpatNum);
                            patient.putAll(detail);
                        } else {
                            patient.put("bedNo", "0");//不能为null,排序会报错
                        }
                        patient.put("currentWardDeptName", deptInfo.get("deptName"));
                    });
                    if (StringUtils.isNotBlank(cardsDTO.getBedNo())) {
                        list = list.stream().filter(patient -> (Integer.parseInt(patient.get("bedNo")) == Integer.parseInt(cardsDTO.getBedNo()))).collect(Collectors.toList());
                    }
                    if (!CollectionUtils.isEmpty(list)) {
                        //排序
                        list = list.stream().sorted(Comparator.comparing(PatientServiceImpl::comparingByBedNo)).collect(Collectors.toList());
                        total = list.size();
                        list = list.stream().skip((cardsDTO.getPage() - 1) * cardsDTO.getPageSize()).limit(cardsDTO.getPageSize()).collect(Collectors.toList());
                    }
                }
                for (Map<String, String> item : list) {
                    item.put("infoType", "operation");//其他
                }
                //排序
                PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
                pageInfo.setTotal(total);
                return ResultGenerator.genOkResult(pageInfo);
            }
        } else {
            String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
            List<Map<String, Object>> patientList = nursePatientMapper.queryPatients(cardsDTO);
            System.out.println("=============================sql耗时" + (System.currentTimeMillis() - time1));
            PageInfo pageInfo2 = new PageInfo(patientList);
            patientList.parallelStream().forEach(patient -> {
                getPatientAge(patient);
                AtomicReference<String> nursingGrade = new AtomicReference<>("");
                String disdaseState = "";
                /*if (patient.get("nursingGrade") != null) {
                    nursingGrade = patient.get("nursingGrade").toString();
                }*/
                List<String> nursingGradeList = Arrays.asList(StateEnum.IJHL.getValue(), StateEnum.IJHLEK.getValue(), StateEnum.IIJHL.getValue(),
                        StateEnum.IIIJHLEK.getValue(), StateEnum.IIIJHL.getValue(), StateEnum.IIIJHLEK.getValue(),
                        StateEnum.YJHL.getValue(), StateEnum.EJHL.getValue(), StateEnum.SJHL.getValue(),
                        StateEnum.TJHL.getValue(), StateEnum.TJHLEK.getValue(), StateEnum.JHBFYJHL.getValue(),
                        StateEnum.JHBFEJHL.getValue(), StateEnum.JHBFTJHL.getValue());
                List<Map<String, String>> nursingGradeLists = nursePatientMapper.queryNursingGradeByInpatNum(Arrays.asList((String)patient.get("inpatNum")), dateTime,nursingGradeList);
                nursingGradeLists.parallelStream().forEach(filterNursingGrade->{
                    if(StateEnum.TJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.TJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFTJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade.set(StateEnum.TJHL.getText());
                    }else if(StateEnum.IJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.YJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFYJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade.set(StateEnum.YJHL.getText());
                    }else if(StateEnum.IIJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IIJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.EJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFEJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade.set(StateEnum.EJHL.getText());
                    }else if(StateEnum.IIIJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IIIJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.SJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                        nursingGrade.set(StateEnum.SJHL.getText());
                    }
                });


                if (patient.get("disdaseState") != null) {
                    disdaseState = patient.get("disdaseState").toString();
                }
                patientComponent.componentBlood(patient);
                patient.put("REPORT_RESULT","");
                patient.put("infoType", "orther");//其他
                patient.put("diagName", getDiagName(patient.get("inpatNum").toString()));
                patient.putAll(getIdentification(patient.get("inpatNum").toString()));//护理登记 病重 药物过敏 危险标识
                patient.put("nursingGrade", nursingGrade.get());
//                patient.put("disdaseState",disdaseState);
            });
            System.out.println("=================================循环耗时" + (System.currentTimeMillis() - time1));
//            patientList.sort((a, b) -> new BigDecimal(a.get("bedNo").toString())
//                    .intValue() - new BigDecimal(b.get("bedNo").toString()).intValue());
            return ResultGenerator.genOkResult(pageInfo2);
        }


        PageInfo pageInfoEmpty = new PageInfo();
        pageInfoEmpty.setList(new ArrayList());

        return ResultGenerator.genOkResult(pageInfoEmpty);
    }


    @Override
    public Result getHealthNum(String inpatNum) {
        String healthNum = nursePatientMapper.queryHealthNum(inpatNum);
        Map<String, String> map = new HashMap<>();
        map.put("healthNum", healthNum == null ? "" : healthNum);
        return ResultGenerator.genOkResult(map);
    }

    private void queryPatientInfoFromHIS(List<Map<String, String>> patientList) {
        for (Map<String, String> map : patientList) {
            if (!map.containsKey("nursingGrade")) {
                map.put("nursingGrade", StringUtils.EMPTY);
            }

            String inpatNum = map.get("inpatNum") == null ? "" : map.get("inpatNum");
            //费别 注释的是正式参数与返回
            String url = cost;
            Map<String, Object> paramCost = new HashMap<>();
            paramCost.put("as_patientId", map.get("inpatNum").replace("-1", ""));
            paramCost.put("operationID", "10001");
            paramCost.put("al_visitId", "1");
            paramCost.put("al_doctor_type", "");

            CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                    HttpClientUtil.sendPost(url, paramCost)).thenApply(x -> x.toString());
            try {
                JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());
                if (jsonObject.getString("data") != null) {
                    Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                    if (cost.get("CHARGE_TYPE").toString().contains("自费")) {
                        map.put("payOff", "自费");
                    } else {
                        map.put("payOff", cost.get("CHARGE_TYPE").toString());
                    }
                }
            } catch (Exception e) {
                logger.error("查询费用明细失败", e);
            }
            // 计算年龄
            Calendar c1 = Calendar.getInstance();
            c1.setTime(DateUtil.stringToDate(map.get("birthDay")));
            Calendar c2 = Calendar.getInstance();
            c2.setTime(DateUtil.stringToDate(map.get("inDatetime")));

            int[] times = DateUtil.getTimeIntervalArray(c2, c1);
            int years = times[0];
            int months = times[1];
            int days = times[2];
            int hours = times[3];
            int minutes = times[4];
            if (years >= 3) {
                map.put("age", years + "岁");
            } else if (years >= 1 && years < 3) {
                map.put("age", years + "岁" + (months == 0 ? "" : months + "月"));
            } else if (years < 1 && months >= 1) {
                map.put("age", months + "月" + (days == 0 ? "" : days + "天"));
            } else if (months < 1 && days >= 1) {
                map.put("age", days + "天");
            } else if (days < 1 && hours >= 1) {
                map.put("age", hours + "小时" + (minutes == 0 ? "" : minutes + "分钟"));
            } else if (hours < 1 && minutes >= 0) {
                map.put("age", minutes + "分钟");
            } else {
                map.put("age", (years == 0 ? "" : years + "岁") + (months == 0 ? "" : months + "月") + (days == 0 ? "" : days + "天") + (hours == 0 ? "" : hours + "小时") + (minutes == 0 ? "" : minutes + "分钟"));
            }


            // 获取血型
            String bloodType = nursePatientMapper.getBloodType(inpatNum);
            map.put("bloodType", StringUtils.isBlank(bloodType) ? "" : bloodType);

            // 过滤诊断
            // 获取护士修改后绑定到文书的诊断id
            String diagName = "";
            String diagId = nurseDiagMapper.queryDiagIdByInpatNum(inpatNum);
            if (StringUtils.isNotBlank(diagId)) {
                // 获取护士修改的诊断名称
                diagName = nurseDiagMapper.queryDiagByDiagId(diagId);
                map.put("diagName", diagName == null ? "" : diagName);
            } else {
                //取病案首页his出院诊断
                if ("prod".equals(activeType)) {
                    String[] inpatNums = inpatNum.split("-");
                    String param = "as_patient_id=" + inpatNums[0] + "&al_visit_id=" + inpatNums[1];
                    JSONObject jsonObject = HttpConnectUtils.sendGet("http://172.20.91.56:8181/P_VsitInfo_Query_03", param);
                    if ("1".equals(jsonObject.get("error_id").toString())) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (Object jsonObject1 : jsonArray) {
                            JSONObject object = JSONObject.parseObject(jsonObject1.toString());
                            if (object.get("DIAGNOSIS_TYPE") != null && "2".equals(object.get("DIAGNOSIS_TYPE").toString())) {
                                diagName = object.get("DIAGNOSIS_DESC").toString();
                                break;
                            }
                        }
                    }
                }
                if (StringUtils.isNotBlank(diagName)) {
                    map.put("diagName", diagName);
                } else {
                    // 获取智慧病历出院诊断/修正诊断/入院诊断
                    diagName = nurseDiagMapper.queryOutHospitalDiag(inpatNum);
                    if (StringUtils.isNotBlank(diagName)) {
                        map.put("diagName", diagName);
                    } else {
                        //获取his门诊诊断
                        diagName = nurseDiagMapper.queryOutpatientDiag(inpatNum);
                        map.put("diagName", diagName == null ? "" : diagName);
                    }
                }
            }

            String bedno = map.get("bedNo");
            // 处理床号,当出院病人床号为0时显示最近一次护理记录单中记录的床号
            if ("0".equals(bedno)) {
                // 获取记录时间最近的护理记录，从中获取床号
                bedno = nurseFileMapper.getLatestBedNo(inpatNum);
                if (StringUtils.isNotEmpty(bedno)) {
                    map.put("bedNo", bedno);
                }
            }

        }
    }

    @Override
    public Result getPatientInfo(String wardDeptId, String medicalNum, String bedNo) {
        Map<String, String> map = nursePatientMapper.getPatientInfoForCard(wardDeptId, medicalNum, bedNo);
        if (map == null) {
            return ResultGenerator.genFailedResult("未查询到病人信息");
        }
        return ResultGenerator.genOkResult(map);
    }

    public Map<String, Object> getIdentification(String inpatNum) {
        Map<String, Object> patientMap = new HashMap<>();
        Map<String, String> conditions = new HashMap<>();
        List<Map<String, String>> condList = patientMapper.queryConditionInfo(inpatNum);//护理登记  病重 药物过敏 危险标识
        for (Map<String, String> cond : condList) {
            if (cond != null) {
                if ("drugBacterialInfection".equals(cond.get("type"))) {
                    conditions.put("drugBacterialInfection", cond.get("data"));
                }
                /*else if ("nursingGrade".equals(cond.get("type"))) {
                    conditions.put("nursingGrade", cond.get("data"));
                }*/
                else if ("responsibleNursePerson".equals(cond.get("type"))) {
                    conditions.put("responsibleNursePerson", cond.get("data"));
                } else if ("disdaseState".equals(cond.get("type"))) {
                    conditions.put("disdaseState", cond.get("data"));
                } else if ("allergicDrugs".equals(cond.get("type"))) {
                    conditions.put("allergicDrugs", toRepeatList(cond.get("data")));
                } else if ("eatingHabits".equals(cond.get("type"))) {
                    conditions.put("eatingHabits", toRepeatList(cond.get("data")));
                }
            }
        }
        List<Map<String, String>> highRiskListOral = patientMapper.queryHighRisk(inpatNum);//高危信息
//		List<Map<String,String>> highRiskListOral = new CopyOnWriteArrayList<>();
//		highRiskLisData.parallelStream().forEach(x ->{
//			if("0b7448e0ced74d1c9ac9c97b0fc7a6ee".equals(x.get("ELEMENT_ID"))){
//				highRiskLisData.parallelStream().forEach(x2 ->{
//					if(x.get("FILE_DATA_ID").equals(x2.get("FILE_DATA_ID")) && x.get("PARENT_ID").equals(x2.get("PARENT_ID")) && "8ceb62574f344a7cb6aae91badba641f".equals(x2.get("ELEMENT_ID"))){
//						Map<String,String> item = new HashMap<>();
//						item.put("fileDate",x.get("fileDate"));
//						item.put("fileDateModify",x.get("gmtModify"));
//						item.put("highRisk",x2.get("highRisk"));
//						if(x.get("DATA_VALUE") ==null){
//							item.put("tplName","");
//						}else{
//							item.put("tplName",x.get("DATA_VALUE"));
//						}
//						highRiskListOral.add(item);
//					}
//				});
//			}
//		});
        Map<String, List<Map<String, String>>> bookMap = null;
        List<Map<String, String>> highRiskList = new ArrayList<>();
        if (highRiskListOral != null && highRiskListOral.size() > 0) {
            bookMap = highRiskListOral.stream().collect(Collectors.groupingBy(b -> b.get("tplName")));
            for (String key : bookMap.keySet()) {
                List<Map<String, String>> keyItem = bookMap.get(key);
                keyItem.sort((a, b) -> (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
                if (keyItem != null && keyItem.size() > 0) {
                    highRiskList.add(keyItem.get(0));
                }
            }
        }

        if (conditions == null) {
            conditions = new HashMap<>();
        }

        List<Map<String, String>> riskList = new CopyOnWriteArrayList();
        highRiskList.parallelStream().forEach(item -> {
            if (StringUtils.isNotBlank(item.get("highRisk")) && StringUtils.isNotBlank(item.get("tplName"))) {
                Map<String, String> riskMap = new HashMap<>();
                if (item.get("highRisk") != null) {//危险程度
                    Integer score = Integer.parseInt(item.get("highRisk").toString());
                    if (score < 25) {
                        riskMap.put("highRisk", "低危");
                    } else if (score >= 25 && score <= 45) {
                        riskMap.put("highRisk", "中危");
                    } else if (score > 45) {
                        riskMap.put("highRisk", "高危");
                    }
                } else {
                    riskMap.put("highRisk", "无");
                }

                riskMap.put("fileDate", item.get("fileDate"));
                riskMap.put("highRiskData", item.get("highRisk"));
                riskMap.put("fileDateModify", item.get("fileDateModify"));
                riskMap.put("tplName", item.get("tplName"));
                String tplName = item.get("tplName");
                Integer score = Integer.parseInt(item.get("highRisk"));
                if (item.get("highRisk") != null) {//危险程度
                    if ("Morse跌倒评分".equals(tplName)) {//跌倒
                        if (score >= 45) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 25 && score <= 44) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 25) {
                            riskMap.put("highRisk", "高危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("儿童跌倒/坠床评分".equals(tplName)) {//跌倒
                        if (score >= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score < 12) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden评分".equals(tplName)) {//braden
                        if (score <= 9) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 10 && score <= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 13 && score <= 14) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 15 && score <= 18) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16))) {
                        if (score <= 10) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 11 && score <= 16) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 17 && score <= 21) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 22) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Barthel评分".equals(tplName) && score <= 40) {
                        if (score <= 40) {
                            riskMap.put("highRisk", "高危");//重度依赖
                        } else if (score >= 41 && score <= 60) {
                            riskMap.put("highRisk", "中危");//中度依赖
                        } else if (score >= 61 && score <= 99) {
                            riskMap.put("highRisk", "低危");//轻度依赖
                        } else if (score == 100) {
                            riskMap.put("highRisk", "");//无需依赖
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                        if (score >= 3) {
                            riskMap.put("highRisk", "高危");//重度
                        } else if (score == 2) {
                            riskMap.put("highRisk", "中危");//中度
                        } else if (score == 1) {
                            riskMap.put("highRisk", "低危");//轻度
                        } else if (score == 0) {
                            riskMap.put("highRisk", "");//正常
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                        if (score > 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 8 && score <= 12) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 8) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) {
                        if (score >= 5) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 3 && score <= 4) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 1 && score <= 2) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }else if ("Padua评分".equals(tplName) && (score >= 4 || (score >= 0 && score <= 3))) {
                        if (score >= 4) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 0 && score <= 3) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }
                } else {
                    riskMap.put("highRisk", "");
                }
                if ("Morse跌倒评分".equals(tplName) && score >= 45) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("儿童跌倒/坠床评分".equals(tplName) && score >= 12) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("Braden评分".equals(tplName) && (score <= 9 || (score >= 10 && score <= 12) || (score >= 13 && score <= 14))) {//braden
                    riskMap.put("highRiskName", "压");
                } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16) || (score >= 17 && score <= 21))) {
                    riskMap.put("highRiskName", "压");
                } else if ("Barthel评分".equals(tplName) && score <= 40) {
                    riskMap.put("highRiskName", "自");
                } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                    riskMap.put("highRiskName", "");
                } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                    riskMap.put("highRiskName", "管");
                } else if (("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) || ("Padua评分".equals(tplName) && score >= 4) ) {
                    riskMap.put("highRiskName", "栓");
                } else {
                    riskMap.put("highRiskName", "");
                }
                if (StringUtils.isNotBlank(riskMap.get("highRiskName"))) {
                    riskList.add(riskMap);
                }
            }
        });
        if (riskList != null && riskList.size() > 0) {
            riskList.sort((a, b) -> (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
        }
        patientMap.put("highRiskList", riskList);
        patientMap.putAll(conditions);
        if (StringUtils.isBlank(conditions.get("allergicDrugs"))) {
            patientMap.put("allergicDrugs", "无");//过敏药物信息
        }
        if (StringUtils.isBlank(conditions.get("disdaseState"))) {
            patientMap.put("disdaseState", "一般");//病情
        }
        if (StringUtils.isBlank(conditions.get("nursingGrade"))) {
            patientMap.put("nursingGrade", "无");//护理等级
        }
        if (StringUtils.isBlank(conditions.get("eatingHabits"))) {
            patientMap.put("eatingHabits", "无");//饮食习惯 (饮食过敏史)
        }
        if (StringUtils.isBlank(conditions.get("drugBacterialInfection"))) {
            patientMap.put("drugBacterialInfection", "0");//多重耐药菌感染信息
        }
        if (StringUtils.isBlank(conditions.get("responsibleNursePerson"))) {
            patientMap.put("responsibleNursePerson", "无");//责任护士
        }
        return patientMap;
    }
    public String toRepeatList(String data){
        List<String> list = new CopyOnWriteArrayList<>();
        if(StringUtils.isNotBlank(data)){
            for(String a1:data.split(",")){
                if(!list.contains(a1)){
                    list.add(a1);
                }
            }
            return StringUtils.join(list,",");

        }else{
            return "";
        }
    }

    private void getPatientAge(Map<String, Object> patientInfo) {
        Integer ageYear = patientInfo.get("ageYear") == null ? 0 : Integer.parseInt(patientInfo.get("ageYear").toString());
        Integer ageMonth = patientInfo.get("ageMonth") == null ? 0 : Integer.parseInt(patientInfo.get("ageMonth").toString());
        Integer ageDay = patientInfo.get("ageDay") == null ? 0 : Integer.parseInt(patientInfo.get("ageDay").toString());
        Integer ageHour = patientInfo.get("ageHour") == null ? 0 : Integer.parseInt(patientInfo.get("ageHour").toString());
        Integer ageMinute = patientInfo.get("ageMinute") == null ? 0 : Integer.parseInt(patientInfo.get("ageMinute").toString());
        StringBuffer ageStr = new StringBuffer();
        if (ageYear != 0) {
            ageStr.append(ageYear + "岁");
        }
        if (ageMonth != 0) {
            ageStr.append(ageMonth + "月");
        }
        if (ageDay != 0) {
            ageStr.append(ageDay + "天");
        }
        if (ageHour != 0) {
            if (ageDay < 29) {              //28天以上不需要小时
                ageStr.append(ageHour + "小时");
            }
        }
        if (ageMinute != 0) {
            ageStr.append(ageMinute + "分钟");
        }
        if (ageStr.length() == 0) {
            ageStr.append(ageHour + "小时");
            ageStr.append(ageMinute + "分钟");
        }
        patientInfo.put("age", ageStr.toString());
    }

    public String getDiagName(String inpatNum) {
        // 过滤诊断
        // 获取护士修改后绑定到文书的诊断id
        String diagName = "";
        String diagId = nurseDiagMapper.queryDiagIdByInpatNum(inpatNum);
        if (StringUtils.isNotBlank(diagId)) {
            // 获取护士修改的诊断名称
            diagName = nurseDiagMapper.queryDiagByDiagId(diagId);
            return diagName;
        } else {
            //取病案首页his出院诊断
            if ("prod".equals(activeType)) {
                String[] inpatNums = inpatNum.split("-");
                String param = "as_patient_id=" + inpatNums[0] + "&al_visit_id=" + inpatNums[1];
                JSONObject jsonObject = HttpConnectUtils.sendGet("http://172.20.91.56:8181/P_VsitInfo_Query_03", param);
                if ("1".equals(jsonObject.get("error_id").toString())) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (Object jsonObject1 : jsonArray) {
                        JSONObject object = JSONObject.parseObject(jsonObject1.toString());
                        if (object.get("DIAGNOSIS_TYPE") != null && "2".equals(object.get("DIAGNOSIS_TYPE").toString())) {
                            diagName = object.get("DIAGNOSIS_DESC").toString();
                            break;
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(diagName)) {
                return diagName;
            } else {
                // 获取智慧病历出院诊断/修正诊断/入院诊断
                diagName = nurseDiagMapper.queryOutHospitalDiag(inpatNum);
                if (StringUtils.isNotBlank(diagName)) {
                    return diagName;
                } else {
                    //获取his门诊诊断
                    diagName = nurseDiagMapper.queryOutpatientDiag(inpatNum);
                    return diagName;
                }
            }
        }
    }

    public Result getWardOverviewNumByWardId(String wardId) {
        //获取系统时间
        String dateTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
        List<WardOverviewLogDTO> wardOverviewLogDTOS = nursePatientMapper.queryWardOverviewLogListByWardId(wardId);
        if (!CollectionUtils.isEmpty(wardOverviewLogDTOS)) {
            //病区的总人数
            Map<String, String> inpatNumMap = nursePatientMapper.queryWardTotalNum(wardId, "total", "in", dateTime);
            //病危：医嘱
            //病重：医嘱
            //特级护理：医嘱
            //一级护理：医嘱
            //陪护：医嘱（陪护）
            //约束：医嘱（肢体约束）
            List<Map<String, String>> orderList = nursePatientMapper.queryWardOrdersNum(wardId, dateTime, inpatNumMap.get("inpatNum"));
            //压力性损伤高危  Braden-Q评分  Braden评分
            //跌倒高危  Morse跌倒评分  儿童跌倒/坠床评分
            //VTE中高危  Caprini评分   Padua评分
            //自理缺陷  Barthel评分
            //导管滑脱高危   导管滑脱危险因素评分
            List<Map<String, String>> assessmentScaleList = nursePatientMapper.queryAssessmentScaleNum(wardId, inpatNumMap.get("inpatNum"));
            //特级护理 一级护理 获取病人信息表NURSING_GRADE
            //List<Map<String, String>> nursingGradeList = nursePatientMapper.queryNursingGradeByWardId(wardId);
            //查询病区代码
            String wardCode = nursePatientMapper.queryDeptCodeByDeptId(wardId);
            List<Map<String, String>> pbstetricWardList = nurseOrdersMapper.queryObstetricWard(wardId,StateEnum.OBSTETRICS_WARD.getValue());

            for (WardOverviewLogDTO wardOverviewLogDTO : wardOverviewLogDTOS) {
                String type = null;
                Map<String, String> map = new ConcurrentHashMap<>();
                //病人总数
                if ("病人总数".equals(wardOverviewLogDTO.getItemName())) {
                    if (inpatNumMap != null) {
                        wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(inpatNumMap.get("count"))));
                        wardOverviewLogDTO.setInpatNum(inpatNumMap.get("inpatNum"));
                    }
                } else if ("产妇总数".equals(wardOverviewLogDTO.getItemName()) || "宝宝总数".equals(wardOverviewLogDTO.getItemName())) {
                    if(!CollectionUtils.isEmpty(pbstetricWardList)){
                        if(wardId.equals(pbstetricWardList.get(0).get("deptId"))){
                            if ("产妇总数".equals(wardOverviewLogDTO.getItemName())) {
                                type = "puerpera";
                            } else if ("宝宝总数".equals(wardOverviewLogDTO.getItemName())) {
                                type = "baby";
                            }
                            map = nursePatientMapper.queryWardTotalNum(wardId, type, "in", dateTime);
                            if (map != null) {
                                wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                                wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                            }
                        }
                    }
                } else if ("今日入院".equals(wardOverviewLogDTO.getItemName())) {
                    map = nursePatientMapper.queryWardTotalNum(wardId, "todayInHospital", "in", dateTime);
                    if (map != null) {
                        wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                        wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                    }
                } else if ("今日出院".equals(wardOverviewLogDTO.getItemName()) || "明日出院".equals(wardOverviewLogDTO.getItemName())) {
                    wardOverviewLogDTO.setOutHospitalMark("out");
                    type = "outHospital";
                    String time = null;
                    if ("今日出院".equals(wardOverviewLogDTO.getItemName())) {
                        time = dateTime;
                    } else if ("明日出院".equals(wardOverviewLogDTO.getItemName())) {
                        Calendar calendar = new GregorianCalendar();
                        calendar.setTime(new Date());
                        calendar.add(calendar.DATE, 1);
                        Date date = calendar.getTime();
                        time = DateUtil.dateToString(date, "yyyy-MM-dd");
                    }
                    map = nursePatientMapper.queryWardTotalNum(wardId, type, "out", time);
                    if (map != null) {
                        wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                        wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                    }
                } else if ("今日转入".equals(wardOverviewLogDTO.getItemName())) {
                    map = nursePatientMapper.queryWardRotatingBedNum(wardId, dateTime, "indept");
                    if (map != null) {
                        wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                        wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                    }
                } else if ("今日手术".equals(wardOverviewLogDTO.getItemName())) {
                    todayOperation(dateTime, inpatNumMap, wardId, wardOverviewLogDTO);
                } else if ("明日手术".equals(wardOverviewLogDTO.getItemName())) {
                    tomorrowOperation(inpatNumMap, wardId, wardOverviewLogDTO);
                } else if ("迁床".equals(wardOverviewLogDTO.getItemName())) {
                    map = nursePatientMapper.queryWardRotatingBedNum(wardId, dateTime, "bed");
                    if (map != null) {
                        wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                        wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                    }
                } else if ("分娩".equals(wardOverviewLogDTO.getItemName())) {
                    if(!CollectionUtils.isEmpty(pbstetricWardList)) {
                        if (wardId.equals(pbstetricWardList.get(0).get("deptId"))) {
                            //map = nursePatientMapper.queryWardChildBirthNum(wardId, dateTime,inpatNumMap.get("inpatNum"));
                            map = nursePatientMapper.queryWardChildBirthNum(wardId, dateTime);
                            if (map != null) {
                                wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                                wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                            }
                        }
                    }
                } else if ("病危".equals(wardOverviewLogDTO.getItemName())) {
                    if (!CollectionUtils.isEmpty(orderList)) {
                        List<Map<String, String>> list = orderList.stream().filter(x -> "6509245E204846129DFDD06BF4E14A5A".equals(x.get("ordersItemId"))).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list)) {
                            wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(list.get(0).get("count"))));
                            wardOverviewLogDTO.setInpatNum(list.get(0).get("inpatNum"));
                        }
                    }
                } else if ("病重".equals(wardOverviewLogDTO.getItemName())) {
                    if (!CollectionUtils.isEmpty(orderList)) {
                        List<Map<String, String>> list = orderList.stream().filter(x -> "455E4CDFB6F1466DAA9A8031138210B8".equals(x.get("ordersItemId"))).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list)) {
                            wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(list.get(0).get("count"))));
                            wardOverviewLogDTO.setInpatNum(list.get(0).get("inpatNum"));
                        }
                    }
                } else if ("特级护理".equals(wardOverviewLogDTO.getItemName())) {
                    if (!CollectionUtils.isEmpty(orderList)) {
                        List<Map<String, String>> list = orderList.stream().filter(x -> ("3F467177035246C8A6CB665E98A5B753".equals(x.get("ordersItemId")) || "30CE2FAE2AA14588BF531110229D4E2D".equals(x.get("ordersItemId"))
                                                                                   || "9AD9F4F93CBD1935E053ED5B14AC284D".equals(x.get("ordersItemId")) )).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list)) {
                            wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(list.get(0).get("count"))));
                            wardOverviewLogDTO.setInpatNum(list.get(0).get("inpatNum"));
                        }
                    }

                } else if ("一级护理".equals(wardOverviewLogDTO.getItemName())) {
                    List<Map<String, String>> list = orderList.stream().filter(x -> ("18D7190F51934ED0919F75CD4B973A6B".equals(x.get("ordersItemId")) || "BD6CFCA1FCFD4D24B291A41394062CE2".equals(x.get("ordersItemId"))
                            || "9AD9F4F93CBE1935E053ED5B14AC284D".equals(x.get("ordersItemId")) || "11405EB160FF4C9489F10BAFB729FAC9".equals(x.get("ordersItemId")) )).collect(Collectors.toList());
                    Set<String> set = new HashSet<>();
                    if (!CollectionUtils.isEmpty(list)) {
                        list.parallelStream().forEach(x->{
                            String[] inpatNums = x.get("inpatNum").split(",");
                            for(String inpat:inpatNums){
                                set.add(inpat);
                            }
                        });
                        wardOverviewLogDTO.setCount(set.size());
                        wardOverviewLogDTO.setInpatNum(StringUtils.join(new ArrayList<String>(set), ","));
                    }

                } else if ("陪护".equals(wardOverviewLogDTO.getItemName())) {
                    if (!CollectionUtils.isEmpty(orderList)) {
                        List<Map<String, String>> list = orderList.stream().filter(x -> "78245A1B96BA4F90A1BD35E1450C77BC".equals(x.get("ordersItemId"))).collect(Collectors.toList());
                        Set<String> set = new HashSet<>();
                        if (!CollectionUtils.isEmpty(list)) {
                            list.parallelStream().forEach(x->{
                                String[] inpatNums = x.get("inpatNum").split(",");
                                for(String inpat:inpatNums){
                                    set.add(inpat);
                                }
                            });
                            wardOverviewLogDTO.setCount(set.size());
                            wardOverviewLogDTO.setInpatNum(StringUtils.join(new ArrayList<String>(set), ","));
                        }
                    }
                } else if ("约束".equals(wardOverviewLogDTO.getItemName())) {
                    if (!CollectionUtils.isEmpty(orderList)) {
                        List<Map<String, String>> list = orderList.stream().filter(x -> "079D323F960F45C9AF70149C63464058".equals(x.get("ordersItemId"))).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list)) {
                            wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(list.get(0).get("count"))));
                            wardOverviewLogDTO.setInpatNum(list.get(0).get("inpatNum"));
                        }
                    }
                } else if ("过敏".equals(wardOverviewLogDTO.getItemName())) {
                    if (inpatNumMap != null) {
                        map = nursePatientMapper.queryAllergyNum(inpatNumMap.get("inpatNum").split(","));
                        if (map != null) {
                            wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                            wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                        }
                    }
                } else if ("压力损伤".equals(wardOverviewLogDTO.getItemName())) {
                    //压力性损伤高危  Braden-Q评分  Braden评分
                    if (!CollectionUtils.isEmpty(assessmentScaleList)) {
                        List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
                        List<Map<String, String>> list1 = assessmentScaleList.stream().filter(x -> "Braden评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) <= 9 || (Integer.parseInt(String.valueOf(x.get("highRisk"))) >= 10 && Integer.parseInt(String.valueOf(x.get("highRisk"))) <= 14))).collect(Collectors.toList());
                        List<Map<String, String>> list2 = assessmentScaleList.stream().filter(x -> "Braden-Q评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) <= 10 || (Integer.parseInt(String.valueOf(x.get("highRisk"))) >= 11 && Integer.parseInt(String.valueOf(x.get("highRisk"))) <= 21))).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list1)) {
                            resultList.addAll(list1);
                        }
                        if (!CollectionUtils.isEmpty(list2)) {
                            resultList.addAll(list2);
                        }
                        Map<String, List<Map<String, String>>> collect = resultList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                        if (collect != null) {
                            wardOverviewLogDTO.setCount(collect.size());
                            String inpatNums = StringUtils.join(new ArrayList<>(collect.keySet()), ",");
                            wardOverviewLogDTO.setInpatNum(inpatNums);
                        }
                    }
                } else if ("跌倒高危".equals(wardOverviewLogDTO.getItemName())) {
                    //跌倒高危  Morse跌倒评分  儿童跌倒/坠床评分
                    if (!CollectionUtils.isEmpty(assessmentScaleList)) {
                        List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
                        List<Map<String, String>> list1 = assessmentScaleList.stream().filter(x -> "Morse跌倒评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) >= 45)).collect(Collectors.toList());
                        List<Map<String, String>> list2 = assessmentScaleList.stream().filter(x -> "儿童跌倒/坠床评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) >= 12)).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list1)) {
                            resultList.addAll(list1);
                        }
                        if (!CollectionUtils.isEmpty(list2)) {
                            resultList.addAll(list2);
                        }
                        Map<String, List<Map<String, String>>> collect = resultList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                        if (collect != null) {
                            wardOverviewLogDTO.setCount(collect.size());
                            String inpatNums = StringUtils.join(new ArrayList<>(collect.keySet()), ",");
                            wardOverviewLogDTO.setInpatNum(inpatNums);
                        }
                    }
                } else if ("VTE".equals(wardOverviewLogDTO.getItemName())) {
                    //VTE中高危  Caprini评分   Padua评分
                    if (!CollectionUtils.isEmpty(assessmentScaleList)) {
                        List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
                        List<Map<String, String>> list1 = assessmentScaleList.stream().filter(x -> "Caprini评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) >= 3)).collect(Collectors.toList());
                        List<Map<String, String>> list2 = assessmentScaleList.stream().filter(x -> "Padua评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) >= 4)).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list1)) {
                            resultList.addAll(list1);
                        }
                        if (!CollectionUtils.isEmpty(list2)) {
                            resultList.addAll(list2);
                        }
                        Map<String, List<Map<String, String>>> collect = resultList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                        if (collect != null) {
                            wardOverviewLogDTO.setCount(collect.size());
                            String inpatNums = StringUtils.join(new ArrayList<>(collect.keySet()), ",");
                            wardOverviewLogDTO.setInpatNum(inpatNums);
                        }
                    }
                } else if ("自理缺陷".equals(wardOverviewLogDTO.getItemName())) {
                    //自理缺陷  Barthel评分
                    if (!CollectionUtils.isEmpty(assessmentScaleList)) {
                        List<Map<String, String>> list1 = assessmentScaleList.stream().filter(x -> "Barthel评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) <= 40)).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list1)) {
                            Map<String, List<Map<String, String>>> collect = list1.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                            if (collect != null) {
                                wardOverviewLogDTO.setCount(list1.size());
                                String inpatNums = StringUtils.join(new ArrayList<>(collect.keySet()), ",");
                                wardOverviewLogDTO.setInpatNum(inpatNums);
                            }
                        }

                    }
                } else if ("导管滑脱".equals(wardOverviewLogDTO.getItemName())) {
                    //导管滑脱高危  导管滑脱危险因素评分
                    if (!CollectionUtils.isEmpty(assessmentScaleList)) {
                        List<Map<String, String>> list1 = assessmentScaleList.stream().filter(x -> "导管滑脱危险因素评分".equals(x.get("tplName")) && StringUtils.isNotBlank(x.get("highRisk")) && (Integer.parseInt(String.valueOf(x.get("highRisk"))) > 12)).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(list1)) {
                            Map<String, List<Map<String, String>>> collect = list1.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                            if (collect != null) {
                                wardOverviewLogDTO.setCount(list1.size());
                                String inpatNums = StringUtils.join(new ArrayList<>(collect.keySet()), ",");
                                wardOverviewLogDTO.setInpatNum(inpatNums);
                            }
                        }

                    }
                } else if ("疼痛".equals(wardOverviewLogDTO.getItemName())) {

                } else if ("危急值".equals(wardOverviewLogDTO.getItemName())) {
                    if (inpatNumMap != null) {
                        map = nursePatientMapper.getPatientsWithCriticalValueByInpatNum(inpatNumMap.get("inpatNum").split(","));
                        if (map != null) {
                            wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                            wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                        }
                    }
                } else if ("体温异常".equals(wardOverviewLogDTO.getItemName())) {
                    if (inpatNumMap != null) {
                        map = nursePatientMapper.queryPatientTemperatureNum(inpatNumMap.get("inpatNum").split(","));
                        if (map != null) {
                            wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                            wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
                        }
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(wardOverviewLogDTOS);
    }

    /**
     * 明日手术
     * @param inpatNumMap
     * @param wardId
     * @param wardOverviewLogDTO
     */
    private void tomorrowOperation(Map<String, String> inpatNumMap, String wardId, WardOverviewLogDTO wardOverviewLogDTO) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime localDate_1 = LocalDateTime.now().plusDays(1);
        LocalDateTime localDate_2 = LocalDateTime.now().plusDays(2);
        String startTime = dateTimeFormatter.format(localDate_1);
        String endTime = dateTimeFormatter.format(localDate_2);
        operation(inpatNumMap, wardId, wardOverviewLogDTO, startTime, endTime);
        /// 之前代码，准备清除
        /*Map<String, String> map;
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(calendar.DATE, 1);
        Date date = calendar.getTime();
        String time = DateUtil.dateToString(date, "yyyy-MM-dd");
        if (inpatNumMap != null) {
            map = nursePatientMapper.getTomorrowOperationNum(inpatNumMap.get("inpatNum").split(","), time);
            if (map != null) {
                wardOverviewLogDTO.setCount(Integer.parseInt(String.valueOf(map.get("count"))));
                wardOverviewLogDTO.setInpatNum(map.get("inpatNum"));
            }
        }*/
    }


    /**
     * 今日手术
     * @param dateTime
     * @param inpatNumMap
     * @param wardId
     * @param wardOverviewLogDTO
     */
    private void todayOperation(String dateTime, Map<String, String> inpatNumMap, String wardId, WardOverviewLogDTO wardOverviewLogDTO) {
        LocalDateTime localDate = LocalDateTime.now().plusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String endTime = formatter.format(localDate);
        operation(inpatNumMap, wardId, wardOverviewLogDTO, dateTime, endTime);
        /// 之前代码，准备清除
        /*//调用his
        Map<String, String> params = new HashMap<String, String>();
        String allInpatNum = inpatNumMap.get("inpatNum");
        if (StringUtils.isNotBlank(allInpatNum)) {
            //去除-1
            String arr[] = allInpatNum.split(",");
            List<String> inpatLiat = new ArrayList<String>();
            for(String inpat:arr){
                inpatLiat.add(inpat.split("-")[0]);
            }
            params.put("inpatNum", StringUtils.join(inpatLiat,","));
            params.put("in_date", dateTime);
            params.put("flag", "1");
            params.put("operationID", ConstantEnum.HIS_OPERATION_10012.getKey());
            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl2, params);
            if (null != jsonObject) {
                if (jsonObject.getString("data") != null) {
                    List<Map<String, String>> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                    });
                    if (!CollectionUtils.isEmpty(list)) {
                        wardOverviewLogDTO.setCount(list.size());
                        List<String> inpatNumList = new CopyOnWriteArrayList();
                        for (Map<String, String> operationMap : list) {
                            if(operationMap!=null && !"0".equals(operationMap.get("sequence"))) {
                                inpatNumList.add(operationMap.get("PATIENT_ID") + "-1");
                            }
                        }
                        wardOverviewLogDTO.setInpatNum(StringUtils.join(inpatNumList, ","));
                        wardOverviewLogDTO.setCount(inpatNumList.size());
                    }
                }
            }
        }*/
    }

    /**
     *
     * 今日手术明日手术公用
     * @param inpatNumMap
     * @param wardId
     * @param wardOverviewLogDTO
     * @param startTime
     * @param endTime
     */
    private void operation(Map<String, String> inpatNumMap, String wardId, WardOverviewLogDTO wardOverviewLogDTO, String startTime, String endTime) {
        // 住院号
        String allInpatNum = inpatNumMap.get("inpatNum");
        // 查询给定时间段手术安排信息
        List<Map<String, Object>> list = nursePatientMapper.getOperationArrangement(wardId, allInpatNum, startTime, endTime);
        if (!CollectionUtils.isEmpty(list)) {
            Set<String> inpatNumList = new HashSet<String>(list.stream().map(l -> (String)l.get("inpatNum")).collect(Collectors.toList()));
            if (!CollectionUtils.isEmpty(inpatNumList)) {
                wardOverviewLogDTO.setCount(inpatNumList.size());
                wardOverviewLogDTO.setInpatNum(String.join(",", inpatNumList));
            }
        }
    }

    @Override
    public Result dischargedSettle(String wardDeptId, String beginTime, String endTime, String queryString, String type, int page, int pageSize) {
        Long t1 = System.currentTimeMillis();
        PageHelper.startPage(page, pageSize);
        List<Map<String, Object>> dischargedPat = patientMapper.dischargedPatient(wardDeptId, beginTime, endTime, queryString);
        String url = cost;
        List<CompletableFuture<Tuple2<String, JSONObject>>> futures = dischargedPat.parallelStream().map(pat -> CompletableFuture.supplyAsync(() -> {
            String patientId = pat.get("medicalNum").toString();
            Map<String, Object> param = new HashMap<>();
            param.put("as_patientId", patientId);
            param.put("operationID", "10001");
            param.put("al_visitId", "1");
            param.put("al_doctor_type", "");
            JSONObject jsonObject = HttpClientUtil.sendPost(url, param);
            if (jsonObject.getString("data") != null) {
                JSONObject cost = JSONArray.parseArray(jsonObject.getString("data"), JSONObject.class).get(0);
                return Tuples.of(patientId, cost);
            } else {
                return null;
            }
        })).collect(Collectors.toList());
        Map<String, JSONObject> patMap = new HashMap<>();
        try {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenApply(v -> futures.stream().map(CompletableFuture::join)
                    .collect(Collectors.toList())).get().stream().filter(Objects::nonNull).forEach(tuple2 -> patMap.put(tuple2.getT1(), tuple2.getT2()));
        } catch (Exception e) {
            logger.error("调用第三方接口报错", e);
        }
        dischargedPat.stream().forEach(map -> {
            JSONObject jsonObject = patMap.get(map.get("medicalNum").toString());
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            if (jsonObject.get("CHARGE_TYPE") == null) {
                map.put("chargeType", "");
            } else if (jsonObject.getString("CHARGE_TYPE").contains("自费")) {
                map.put("chargeType", "自费");
            } else {
                map.put("chargeType", jsonObject.getString("CHARGE_TYPE"));
            }
            map.put("classFlag", StringUtils.isBlank(jsonObject.getString("CLASS_FLAG")) ? "0" : jsonObject.getString("CLASS_FLAG"));
            map.put("specialFlag", StringUtils.isBlank(jsonObject.getString("SPECIAL_FLAG")) ? "0" : jsonObject.getString("SPECIAL_FLAG"));
            map.put("totalCostSettle", new BigDecimal(StringUtils.isBlank(jsonObject.getString("TOTAL_COST_SETTLE")) ? "0" : jsonObject.getString("TOTAL_COST_SETTLE")));
            map.put("totalCost", new BigDecimal(StringUtils.isBlank(jsonObject.getString("TOTAL_COST")) ? "0" : jsonObject.getString("TOTAL_COST")));
        });
        Long t2 = System.currentTimeMillis();
        logger.info("查询耗时{}", t2 - t1);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(dischargedPat);
        return ResultGenerator.genOkResult(pageInfo);
    }


    private static String fetchGroupInpatNum(Map<String, String> map) {
        return map.get("inpatNum");
    }


    public Result handNumbness(String wardId){
        if ("95037CF5C9465245E053ED5B14ACFD88".equals(wardId) || "95037CF5C9475245E053ED5B14ACFD88".equals(wardId)
                || "F0F3BC5868CE47F583CB08EC6E46B1D6".equals(wardId) || "5D04523554944A30A5FB81F57E985763".equals(wardId)) {
            return ResultGenerator.genOkResult(1);
        }
        return ResultGenerator.genOkResult(0);
    }


    public Result querySpecialWard(String wardId,String varCode){
        List<Map<String, String>> pbstetricWardList = nurseOrdersMapper.queryObstetricWard(wardId,varCode);
        return ResultGenerator.genOkResult(pbstetricWardList);
    }

}
